package com.tomato.study.jvm.datastructure;

/**
 * 树
 *
 * @author lizhifu
 * @date 2022/4/25
 */
public class Tree {
    /**
     * 树容量
     */
    private int capacity;
    /**
     * 树节点数量
     */
    private int nodeCount;
    /**
     * 存放Node类型的数组
     */
    private Node[] elements;

    /**
     * 设置数组容量
     * @param capacity
     */
    public Tree(int capacity) {
        this.capacity = capacity;
        this.elements = new Node[capacity];
    }
    /**
     * 是否空树
     */
    public boolean isEmpty(){
        return nodeCount == 0;
    }

    /**
     * 是否满树
     * @return
     */
    public boolean isFull(){
        return nodeCount == capacity;
    }
    /**
     * 插入节点
     */
    public void insert(Node node){
        if (nodeCount == capacity){
            throw new RuntimeException("树已满");
        }
        elements[nodeCount++] = node;
    }

    /**
     * 删除节点
     * @param node
     */
    public void delete(Node node){
        int index = 0;
        for (int i = 0; i < nodeCount; i++) {
            if (elements[i].equals(node)){
                index = i;
                break;
            }
        }
        for (int i = index; i < nodeCount - 1; i++) {
            elements[i] = elements[i + 1];
        }
        nodeCount--;
    }

    /**
     * 查找节点
     * @param node
     * @return
     */
    public Node find(Node node){
        for (int i = 0; i < nodeCount; i++) {
            if (elements[i].equals(node)){
                return elements[i];
            }
        }
        return null;
    }

    /**
     * 遍历树
     */
    public void traverse(){
        for (int i = 0; i < nodeCount; i++) {
            System.out.println(elements[i]);
        }
    }
}
